package com.duowei.diandan.view;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.View;

public class ScanningView extends View {

    private Paint mPaint = new Paint();
    private int mPosY = 0;
    private boolean mRunAnimation = true;
    private boolean mShowLine = true;
    private Handler mHandler;
    private Runnable mRefreshRunnable;
    private boolean mIsGoingDown = true;
    private int mHeight;

    public ScanningView(Context context) {
        super(context);
        init();
    }

    public ScanningView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        mHeight = canvas.getHeight();
        if (mShowLine) {
            canvas.drawLine(0, mPosY, canvas.getWidth(), mPosY, mPaint);
        }
        if (mRunAnimation) {
            mHandler.postDelayed(mRefreshRunnable, 50);
        }
    }

    private void init() {
        mPaint.setColor(Color.WHITE);
        mPaint.setStrokeWidth(5);
        mHandler = new Handler();
        mRefreshRunnable = this::refreshView;
    }

    public void startAnimation() {
        mRunAnimation = true;
        mShowLine = true;
        invalidate();
    }

    public void stopAnimation() {
        mRunAnimation = false;
        mShowLine = false;
        reset();
        invalidate();
    }

    private void reset() {
        mPosY = 0;
        mIsGoingDown = true;
    }

    private void refreshView() {
        if (mIsGoingDown) {
            mPosY += 5;
            if (mPosY > mHeight) {
                mPosY = mHeight;
                mIsGoingDown = false;
            }
        } else {
            mPosY -= 5;
            if (mPosY < 0) {
                mPosY = 0;
                mIsGoingDown = true;
            }
        }

        invalidate();
    }
}
